<template>
  <div class="app-container">
    <!-- 操作按钮区域 -->
    <div class="mb10 flex justify-between">
      <div>
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
        <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="handleBatch">批量删除</el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-input
        v-model="queryParams.team_name"
        placeholder="请输入班组名称"
        clearable
        style="width: 300px"
        @keyup.enter.native="handleQuery"
      />
      <el-select
        v-model="queryParams.team_type"
        placeholder="请选择班组类型"
        clearable
        style="width: 200px"
      >
        <el-option label="生产班组" value="1" />
        <el-option label="研发班组" value="2" />
      </el-select>
      <el-button type="primary" style="margin-left: 10px" @click="resetQuery">重置</el-button>
      <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      :data="teamList"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="创建时间" align="center" prop="create_time" width="180">
        <template slot-scope="scope">
          {{ scope.row.create_time ? scope.row.create_time.split(' ')[0] : '' }}
        </template>
      </el-table-column>
      <el-table-column label="班组编码" align="center" prop="team_code" width="150" />
      <el-table-column label="班组名称" align="center" prop="team_name" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="所属生产线" align="center" prop="production_line_name" :show-overflow-tooltip="true" />
      <el-table-column label="所属车间" align="center" prop="workshop_name" :show-overflow-tooltip="true" />
      <el-table-column label="状态" align="center" prop="team_status" width="80">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.team_status === '1'">启用</el-tag>
          <el-tag type="danger" v-else>禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="班组人员" align="center" prop="team_num" width="80" />
      <el-table-column label="创建人" align="center" prop="create_by" width="100" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" style="color: #409EFF;">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" style="color: #F56C6C;">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改班组对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 基础信息 -->
        <div class="section-header">
          <div class="section-title">
            <div class="blue-line"></div>
            <span>基础信息</span>
          </div>
        </div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="班组编码" prop="team_code">
              <el-input v-model="form.team_code" placeholder="请输入内容" :disabled="true">
                <el-button v-if="title === '添加班组'" slot="append" icon="el-icon-refresh" @click="getAutoTeamCode">自动编号</el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班组名称" prop="team_name">
              <el-input v-model="form.team_name" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属车间" prop="workshop_id">
              <el-select 
                v-model="form.workshop_id" 
                placeholder="请选择" 
                @change="handleWorkshopChange"
                @click.native="loadWorkshopOptions" 
                style="width: 100%"
              >
                <el-option
                  v-for="item in workshopOptions"
                  :key="item.workshop_id"
                  :label="item.workshop_name"
                  :value="item.workshop_id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属生产线" prop="production_line_id">
              <el-select 
                v-model="form.production_line_id" 
                placeholder="请选择" 
                @change="handleProductionLineChange"
                style="width: 100%"
              >
                <el-option
                  v-for="item in productionLineOptions"
                  :key="item.production_line_id"
                  :label="item.production_line_name"
                  :value="item.production_line_id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-switch v-model="form.team_status" active-value="1" inactive-value="0" active-color="#13ce66" inactive-color="#ff4949" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班组类型" prop="team_type" v-show="false">
              <el-select v-model="form.team_type" placeholder="请选择班组类型" style="width: 100%">
                <el-option label="生产班组" value="1" />
                <el-option label="研发班组" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容" />
        </el-form-item>

        <!-- 班组人员 -->
        <div class="section-header">
          <div class="section-title">
            <div class="blue-line"></div>
            <span>班组人员</span>
          </div>
        </div>
        <div class="team-members-container">
          <div class="team-members-actions">
            <el-button type="primary" icon="el-icon-plus" size="mini" style="margin-right: 0;" @click="handleAddMember">添加人员</el-button>
          </div>
          <div v-if="title === '添加班组' && teamMembers.length === 0" style="margin-bottom: 10px; color: #F56C6C;">
            当前没有班组人员数据
          </div>
          <div v-if="title === '添加班组' && teamMembers.length > 0" style="margin-bottom: 10px; color: #67C23A;">
            已加载 {{teamMembers.length}} 名班组人员
          </div>
          <el-table 
            :data="teamMembers" 
            border 
            class="team-members-table"
            :header-cell-style="{background:'#fafafa', color:'#606266'}"
            empty-text="暂无数据"
            height="180"
            size="small"
            style="width: 100%;"
          >
            <el-table-column type="index" label="序号" width="50" align="center" />
            <el-table-column prop="employee_id" label="员工ID" align="center" width="100">
              <template slot-scope="scope">
                <span>{{ scope.row.employee_id }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="employee_name" label="姓名" align="center" width="80">
              <template slot-scope="scope">
                <span>{{ scope.row.employee_name }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="nickname" label="用户昵称" align="center" width="100">
              <template slot-scope="scope">
                <span>{{ scope.row.nickname }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="department" label="所属部门" align="center" width="140">
              <template slot-scope="scope">
                <span>{{ scope.row.department }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="phone" label="手机号码" align="center" width="120">
              <template slot-scope="scope">
                <span>{{ scope.row.phone }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="text" style="color: #F56C6C;" @click="removeMember(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加班组成员对话框 -->
    <el-dialog title="添加班组成员" :visible.sync="memberDialogVisible" width="800px" append-to-body>
      <el-form :model="memberForm" ref="memberForm" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="员工ID" prop="employee_id">
              <el-input v-model="memberForm.employee_id" placeholder="请输入员工ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="employee_name">
              <el-input v-model="memberForm.employee_name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickname">
              <el-input v-model="memberForm.nickname" placeholder="请输入用户昵称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="department">
              <el-input v-model="memberForm.department" placeholder="请输入部门" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="memberForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="memberDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAddMember">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 员工选择对话框 -->
    <el-dialog title="选择员工" :visible.sync="userSelectVisible" width="900px" append-to-body>
      <!-- 搜索条件 -->
      <el-form :model="userQueryParams" ref="userQueryForm" :inline="true">
        <el-form-item label="员工姓名" prop="userName">
          <el-input v-model="userQueryParams.userName" placeholder="请输入员工姓名" clearable size="small" @keyup.enter.native="handleUserQuery" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input v-model="userQueryParams.phonenumber" placeholder="请输入手机号码" clearable size="small" @keyup.enter.native="handleUserQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleUserQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="handleUserReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 员工列表 -->
      <el-table v-loading="userLoading" :data="userList" @selection-change="handleUserSelectChange" style="width: 100%">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column label="用户ID" align="center" prop="userId" width="80" />
        <el-table-column label="用户名称" align="center" prop="userName" :show-overflow-tooltip="true" />
        <el-table-column label="用户昵称" align="center" prop="nickName" :show-overflow-tooltip="true" />
        <el-table-column label="部门" align="center" prop="dept.deptName" :show-overflow-tooltip="true" />
        <el-table-column label="手机号码" align="center" prop="phonenumber" width="120" />
        <el-table-column label="状态" align="center" width="80">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.status === '0'">正常</el-tag>
            <el-tag type="danger" v-else>停用</el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="userTotal > 0"
        :total="userTotal"
        :page.sync="userQueryParams.pageNum"
        :limit.sync="userQueryParams.pageSize"
        @pagination="loadUserList"
      />
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="userSelectVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSelectUsers">确 认 选 择</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTeam, getTeam, delTeam, addTeam, updateTeam, exportTeam, getworkshop, getlines, listuser, delCustomers } from "@/api/basic/team";
import { getAutoNumbers, getAutoNumbersConsume } from "@/api/basic/numbers";


export default {
  name: "BasicTeam",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 班组表格数据
      teamList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        searchValue: undefined,
        team_name: undefined,
        team_type: undefined,
        team_status: undefined
      },
      // 车间选项
      workshopOptions: [],
      // 生产线选项
      productionLineOptions: [],
      // 表单参数
      form: {
        team_id: undefined,
        team_code: undefined,
        team_name: undefined,
        workshop_id: undefined,
        workshop_name: undefined,
        production_line_id: undefined,
        production_line_name: undefined,
        team_status: "1",
        team_num: 5,
        team_type: "1",
        remarks: undefined
      },
      // 表单校验
      rules: {
        team_code: [
          { required: true, message: "班组编码不能为空", trigger: "blur" }
        ],
        team_name: [
          { required: true, message: "班组名称不能为空", trigger: "blur" }
        ],
        workshop_id: [
          { required: true, message: "所属车间不能为空", trigger: "change" }
        ],
        production_line_id: [
          { required: true, message: "所属生产线不能为空", trigger: "change" }
        ]
      },
      // 班组成员列表
      teamMembers: [],
      // 原始班组成员列表（用于修改时比较变化）
      originalTeamMembers: [],
      // 添加班组成员对话框
      memberDialogVisible: false,
      // 添加班组成员表单
      memberForm: {
        employee_id: undefined,
        employee_name: undefined,
        nickname: undefined,
        department: undefined,
        phone: undefined
      },
      // 员工列表数据
      userList: [],
      // 员工列表总数
      userTotal: 0,
      // 员工列表加载状态
      userLoading: false,
      // 员工查询参数
      userQueryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined
      },
      // 员工选择对话框
      userSelectVisible: false,
      // 选中的员工列表
      selectedUsers: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询班组列表 */
    getList() {
      this.loading = true;
      const params = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        searchValue: this.queryParams.searchValue,
        team_name: this.queryParams.team_name,
        team_type: this.queryParams.team_type,
        team_status: this.queryParams.team_status
      };
      
      listTeam(params).then(response => {
        this.teamList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    
    /** 车间选择框变化事件 */
    handleWorkshopChange(value) {
      this.form.production_line_id = undefined;
      this.form.production_line_name = undefined;
      
      if (value) {
        // 先从本地缓存中查找车间名称
        const workshop = this.workshopOptions.find(item => item.workshop_id == value);
        if (workshop) {
          this.form.workshop_name = workshop.workshop_name;
        }
        
        // 获取车间详情以确保数据准确
        getworkshop({
          workshop_id: value
        }).then(response => {
          console.log("车间详情:", response);
          if (response.code === 200) {
            // 判断数据位置
            if (response.rows && Array.isArray(response.rows) && response.rows.length > 0) {
              // 如果数据在rows中
              this.form.workshop_name = response.rows[0].workshop_name;
            } else if (response.data && Array.isArray(response.data) && response.data.length > 0) {
              // 如果返回的是数组，取第一个元素
              this.form.workshop_name = response.data[0].workshop_name;
            } else if (response.data && typeof response.data === 'object') {
              // 如果是单个对象
              this.form.workshop_name = response.data.workshop_name;
            } else if (!this.form.workshop_name) {
                console.warn("未找到车间名称");
                this.$message.warning("未能获取车间名称");
            }
          } else {
            console.warn("获取车间详情失败:", response.msg);
          }
        }).catch(error => {
          console.error("获取车间详情失败:", error);
        });
        
        // 清空生产线选项
        this.productionLineOptions = [];
        
        // 重新获取生产线选项
        getlines({
          basicWorkshop: {
            workshop_id: value
          },
          is_delete: 0
        }).then(response => {
          console.log("生产线查询结果:", response);
          if (response.code === 200) {
            // 判断数据位置
            if (response.rows && Array.isArray(response.rows)) {
              this.productionLineOptions = response.rows;
            } else if (response.data && Array.isArray(response.data)) {
              this.productionLineOptions = response.data;
            } else {
              console.warn("获取生产线数据格式异常");
            }
          }
        }).catch(error => {
          console.error("获取生产线选项失败:", error);
        });
      } else {
        this.productionLineOptions = [];
        this.form.workshop_name = undefined;
      }
    },
    
    /** 重置表单数据 */
    reset() {
      this.form = {
        team_id: undefined,
        team_code: undefined,
        team_name: undefined,
        workshop_id: undefined,
        workshop_name: undefined,
        production_line_id: undefined,
        production_line_name: undefined,
        team_status: "1",
        team_num: 5,
        team_type: "1",
        remarks: undefined
      };
      this.teamMembers = [];
      this.resetForm("form");
    },
    
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    
    /** 表单提交 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 确保已经获取到生产线名称
          if (this.form.production_line_id && !this.form.production_line_name) {
            getlines({
              basicProductionline: {
                production_line_id: this.form.production_line_id
              },
              is_delete: 0
            }).then(response => {
              if (response.code === 200 && response.data) {
                if (Array.isArray(response.data) && response.data.length > 0) {
                  this.form.production_line_name = response.data[0].production_line_name || response.data[0].line_name;
                } else {
                  this.form.production_line_name = response.data.production_line_name || response.data.line_name;
                }
                this.submitFormData();
              }
            }).catch(() => {
              this.$modal.msgError("获取生产线名称失败");
            });
          } else {
            this.submitFormData();
          }
        }
      });
    },
    
    /** 提交表单数据 */
    async submitFormData() {
      // 检查班组编号是否存在
      if (!this.form.team_code) {
        this.$modal.msgError("班组编号不能为空");
        return;
      }

      // 如果是新增模式且有班组编号，在提交前获取真正的编号
      if (this.title === "添加班组" && this.form.team_code) {
        try {
          const response = await getAutoNumbersConsume(34);
          if (typeof response === 'string') {
            this.form.team_code = response;
          } else if (response && response.msg) {
            this.form.team_code = response.msg;
          }
        } catch (error) {
          this.$modal.msgError('获取最终班组编号失败');
          return;
        }
      }

      // 计算团队成员数量
      this.form.team_num = this.teamMembers.length;
      
      // 准备团队成员数据
      const teamMembersData = this.teamMembers.map(member => ({
        user_id: member.employee_id,  // 将employee_id映射为后端期望的user_id
        employee_name: member.employee_name,
        nickname: member.nickname,
        department: member.department,
        phone: member.phone
      }));
      
      // 准备提交的完整数据
      const submitData = {
        ...this.form,
        workshop_id: this.form.workshop_id,
        workshop_name: this.form.workshop_name,
        production_line_id: this.form.production_line_id,
        production_line_name: this.form.production_line_name,
        basicTeamdetails: teamMembersData,  // 主要字段
        teamMembers: teamMembersData,       // 备用字段1
        memberList: teamMembersData         // 备用字段2
      };
      
      // 记录表单提交详情
      console.log("提交的数据:", submitData);
      
      if (this.form.team_id !== undefined) {
        // 修改班组时，记录操作类型
        console.log("执行修改班组操作，班组ID:", this.form.team_id);
        console.log("原始班组人员数量:", this.originalTeamMembers.length);
        console.log("当前班组人员数量:", this.teamMembers.length);
        
        // 分析班组人员变化
        const hasChanges = this.detectTeamMemberChanges();
        console.log("班组人员是否有变化:", hasChanges);
        
        // 获取更新后的班组人员数量
        const updatedTeamSize = this.teamMembers.length;
        submitData.team_num = updatedTeamSize;
        
        // 输出变化细节
        if (hasChanges) {
          console.log("班组人员发生变化，原始数量:", this.originalTeamMembers.length, "变更后数量:", updatedTeamSize);
        }
        
        // 更新团队
        updateTeam(submitData).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      } else {
        // 新增班组逻辑保持不变
        addTeam(submitData).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      }
    },
    
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.team_name = undefined;
      this.queryParams.team_type = undefined;
      this.queryParams.team_status = undefined;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.team_id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加班组";
      
      // 加载车间选项
      this.loadWorkshopOptions();
      
      // 初始化空的成员列表，不再添加默认示例
      this.teamMembers = [];
    },
    
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const teamId = row.team_id;
      
      // 先设置初始值，避免出现undefined错误
      this.form.team_code = row.team_code || '';
      this.form.team_name = row.team_name || '';
      this.form.team_status = row.team_status || '1';
      this.form.team_type = row.team_type || '1';
      
      // 显示弹窗
      this.open = true;
      this.title = "修改班组";
      
      // 加载车间选项
      this.loadWorkshopOptions();
      
      getTeam(teamId).then(response => {
        console.log("获取班组详情响应:", response);
        // 确保响应中有数据
        if (response && response.code === 200) {
          let teamData = null;
          
          // 处理可能的不同数据结构
          if (response.data) {
            teamData = response.data;
          } else if (response.rows && response.rows.length > 0) {
            teamData = response.rows[0];
          }
          
          if (teamData) {
            console.log("获取到的班组数据:", teamData);
            
            // 确保所有必须的字段都存在
            this.form = {
              team_id: teamData.team_id || row.team_id,
              team_code: teamData.team_code || row.team_code || '',
              team_name: teamData.team_name || row.team_name || '',
              workshop_id: teamData.workshop_id || '',
              workshop_name: teamData.workshop_name || '',
              production_line_id: teamData.production_line_id || '',
              production_line_name: teamData.production_line_name || '',
              team_status: teamData.team_status || '1',
              team_num: teamData.team_num || 0,
              team_type: teamData.team_type || '1',
              remarks: teamData.remarks || '',
            };
            
            console.log("设置表单数据:", this.form);
            
            // 如果有车间ID，获取对应的生产线选项
            if (this.form.workshop_id) {
              this.getProductionLineOptions(this.form.workshop_id);
            }
            
                          // 加载班组成员
              console.log("后端返回的班组成员数据:", teamData);
              
              // 检查不同可能的成员数据结构
              let memberData = [];
              if (teamData.basicTeamdetails && Array.isArray(teamData.basicTeamdetails)) {
                memberData = teamData.basicTeamdetails;
                console.log("从basicTeamdetails获取成员数据:", memberData);
              } else if (teamData.teamMembers && Array.isArray(teamData.teamMembers)) {
                memberData = teamData.teamMembers;
                console.log("从teamMembers获取成员数据:", memberData);
              } else if (teamData.memberList && Array.isArray(teamData.memberList)) {
                memberData = teamData.memberList;
                console.log("从memberList获取成员数据:", memberData);
              } else if (response && response.rows && Array.isArray(response.rows)) {
                // 直接从响应的rows中获取成员数据
                memberData = response.rows;
                console.log("从response.rows获取成员数据:", memberData);
              }
              
              if (memberData && memberData.length > 0) {
                console.log("处理成员数据，第一条记录:", memberData[0]);
                // 处理成员数据
                this.teamMembers = memberData.map(item => ({
                  employee_id: item.user_id || item.userId || '',
                  employee_name: item.user_name || item.userName || item.employee_name || '',
                  nickname: item.nick_name || item.nickName || item.nickname || '',
                  department: item.dept_name || (item.dept ? item.dept.deptName : '') || item.department || '',
                  phone: item.phonenumber || item.phone || ''
                }));
                
                // 保存原始成员数据，用于后续比较
                this.originalTeamMembers = JSON.parse(JSON.stringify(this.teamMembers));
                
                console.log("处理后的班组成员数据:", this.teamMembers);
                console.log("保存的原始班组成员数据:", this.originalTeamMembers);
              } else {
                console.log("没有找到班组成员数据");
                this.teamMembers = [];
                this.originalTeamMembers = [];
              }
          } else {
            this.$modal.msgError("获取班组数据失败");
          }
        } else {
          this.$modal.msgError("获取班组详情失败: " + (response?.msg || "未知错误"));
        }
      }).catch(error => {
        console.error("获取班组详情出错:", error);
        this.$modal.msgError("获取班组详情出错: " + error.message);
      });
    },
    
    /** 删除按钮操作 */
    handleDelete(row) {
      const teamId = row.team_id;
      console.log("执行删除操作，班组ID:", teamId);
      this.$modal.confirm('是否确认删除班组编号为"' + row.team_code + '"的数据项?').then(function() {
        return delTeam(teamId);
      }).then(response => {
        console.log("删除班组响应:", response);
        if (response.code === 200) {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        } else {
          this.$modal.msgError("删除失败: " + (response.msg || "未知错误"));
        }
      }).catch(error => {
        console.error("删除班组出错:", error);
        this.$modal.msgError("删除出错: " + error.message);
      });
    },
    
    /** 批量删除按钮 */
    handleBatch() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请至少选择一条记录");
        return;
      }
      
      console.log("执行批量删除操作，选中ID数组:", this.ids);
      this.$modal.confirm('确认要删除选中的 ' + this.ids.length + ' 条班组记录?').then(() => {
        // 将数组转换为逗号分隔的字符串
        const idsStr = this.ids.join(',');
        return delCustomers(idsStr);
      }).then(response => {
        console.log("批量删除响应:", response);
        if (response.code === 200) {
          this.getList();
          this.$modal.msgSuccess("批量删除成功");
        } else {
          this.$modal.msgError("批量删除失败: " + (response.msg || "未知错误"));
        }
      }).catch(error => {
        console.error("批量删除出错:", error);
        this.$modal.msgError("批量删除出错: " + error.message);
      });
    },
    
    /** 导入按钮操作 */
    handleImport() {
      this.$modal.msgInfo("导入功能待实现");
    },
    
    /** 导出按钮操作 */
    handleExport() {
      const params = { ...this.queryParams };
      this.$modal.confirm('是否确认导出所有班组数据项?').then(() => {
        this.exportLoading = true;
        return exportTeam(params);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
        this.exportLoading = false;
      });
    },

    /** 添加班组成员 */
    handleAddMember() {
      // 重置表单
      this.$nextTick(() => {
        if (this.$refs["memberForm"]) {
          this.$refs["memberForm"].resetFields();
        }
      });
      
      // 显示选择员工对话框
      this.userSelectVisible = true;
      
      // 加载员工列表
      this.loadUserList();
    },

    /** 确认添加班组成员 */
    confirmAddMember() {
      this.$refs["memberForm"].validate(valid => {
        if (valid) {
          this.teamMembers.push({
            employee_id: this.memberForm.employee_id,
            employee_name: this.memberForm.employee_name,
            nickname: this.memberForm.nickname,
            department: this.memberForm.department,
            phone: this.memberForm.phone
          });
          this.memberDialogVisible = false;
          this.$modal.msgSuccess("添加成功");
        }
      });
    },

    /** 删除班组成员 */
    removeMember(index) {
      this.$modal.confirm('是否确认删除该班组成员?').then(() => {
        this.teamMembers.splice(index, 1);
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 获取自动编号 */
    getAutoTeamCode() {
      // 如果是编辑模式且已有班组编号，则不重新获取
      if (this.title !== "添加班组" && this.form.team_code) {
        console.log("编辑模式，保留原班组编号:", this.form.team_code);
        return;
      }
      
      this.$modal.loading("正在获取自动编码...");
      
      // 调用获取自动编码接口，传入编码类型参数值为34（班组编号）
      getAutoNumbers(34).then(response => {
        this.$modal.closeLoading();
        
        console.log("自动编码API返回数据:", response);
        
        // 检查各种可能的返回格式
        if (typeof response === 'string') {
          // 直接返回字符串编号
          this.form.team_code = response;
          return;
        }
        
        if (response === null || response === undefined) {
          this.$modal.msgError("获取自动编号失败：返回为空");
          return;
        }
        
        // 检查常见的接口返回格式
        if (response.code === 200 || response.code === 0) {
          // 标准若依框架返回格式
          if (response.data) {
            this.form.team_code = response.data;
          } else if (response.msg && typeof response.msg === 'string') {
            this.form.team_code = response.msg;
          } else if (response.rows && response.rows.length > 0) {
            this.form.team_code = response.rows[0];
          } else {
            // 无法从标准字段获取，尝试直接读取
            console.warn("无法从标准返回字段获取编号，尝试直接读取response");
            this.form.team_code = "BZ" + new Date().getTime(); // 生成临时编号
          }
        } else {
          console.error("获取自动编号失败，响应：", response);
          this.$modal.msgError("获取自动编号失败：" + (response.msg || "未知错误"));
        }
      }).catch(error => {
        this.$modal.closeLoading();
        console.error("获取自动编号失败:", error);
        this.$modal.msgError("获取自动编号失败: " + (error.message || "未知错误"));
      });
    },

    /** 加载车间选项 */
    loadWorkshopOptions() {
      // 查询所有车间
      getworkshop({}).then(response => {
        console.log("车间查询结果:", response);
        if (response.code === 200) {
          // 判断返回数据的结构
          if (response.rows && Array.isArray(response.rows)) {
            // 如果数据在rows字段中
            this.workshopOptions = response.rows;
            console.log("赋值后的车间选项:", this.workshopOptions);
          } else if (response.data && Array.isArray(response.data)) {
            // 如果数据在data字段中
            this.workshopOptions = response.data;
            console.log("赋值后的车间选项:", this.workshopOptions);
          } else {
            console.warn("车间数据格式异常:", response);
            this.$message.warning("获取车间数据格式异常");
          }
        } else {
          this.$message.error("获取车间列表失败: " + (response.msg || "未知错误"));
        }
      }).catch(error => {
        console.error("获取车间选项失败:", error);
        this.$message.error("获取车间选项失败: " + error.message);
      });
    },

    /** 生产线选择框变化事件 */
    handleProductionLineChange(value) {
      if (value) {
        // 从已加载的生产线选项中获取名称
        const selectedLine = this.productionLineOptions.find(line => 
          line.production_line_id == value || line.line_id == value
        );
        
        if (selectedLine) {
          this.form.production_line_name = selectedLine.production_line_name || selectedLine.line_name;
          console.log("已设置生产线名称:", this.form.production_line_name);
          return;
        }
        
        // 如果在本地数据中未找到，则通过API获取
        getlines({
          basicProductionline: {
            production_line_id: value
          },
          is_delete: 0
        }).then(response => {
          console.log("获取生产线详情:", response);
          if (response.code === 200) {
            if (response.data) {
            if (Array.isArray(response.data) && response.data.length > 0) {
              this.form.production_line_name = response.data[0].production_line_name || response.data[0].line_name;
            } else {
              this.form.production_line_name = response.data.production_line_name || response.data.line_name;
            }
            } else if (response.rows && Array.isArray(response.rows) && response.rows.length > 0) {
              this.form.production_line_name = response.rows[0].production_line_name || response.rows[0].line_name;
            }
            console.log("API获取到生产线名称:", this.form.production_line_name);
          } else {
            console.warn("获取生产线详情失败:", response.msg);
          }
        }).catch(error => {
          console.error("获取生产线详情失败:", error);
        });
      } else {
        this.form.production_line_name = undefined;
      }
    },

    /** 加载员工选项 */
    loadUserList() {
      this.userLoading = true;
      
      // 构建查询参数 - 适配SysUser对象参数格式
      const params = {
        pageNum: this.userQueryParams.pageNum,
        pageSize: this.userQueryParams.pageSize
      };
      
      // 添加查询条件
      if (this.userQueryParams.userName && this.userQueryParams.userName.trim() !== '') {
        params.userName = this.userQueryParams.userName.trim();
      }
      
      if (this.userQueryParams.phonenumber && this.userQueryParams.phonenumber.trim() !== '') {
        params.phonenumber = this.userQueryParams.phonenumber.trim();
      }
      
      console.log("查询员工列表参数:", params);
      
      // 调用接口
      listuser(params).then(response => {
        console.log("员工查询结果:", response);
        if (response.code === 200) {
          if (response.rows && Array.isArray(response.rows)) {
            this.userList = response.rows;
            this.userTotal = response.total || 0;
          } else if (response.data && Array.isArray(response.data)) {
            this.userList = response.data;
            this.userTotal = response.total || 0;
          } else {
            console.warn("员工数据格式异常");
            this.userList = [];
            this.userTotal = 0;
          }
        } else {
          this.$message.error("获取员工列表失败: " + (response.msg || "未知错误"));
          this.userList = [];
          this.userTotal = 0;
        }
        this.userLoading = false;
      }).catch(error => {
        console.error("获取员工列表失败:", error);
        this.$message.error("获取员工列表失败: " + error.message);
        this.userList = [];
        this.userTotal = 0;
        this.userLoading = false;
      });
    },

    /** 用户查询按钮操作 */
    handleUserQuery() {
      // 确保使用最新的搜索条件
      this.userQueryParams.pageNum = 1;
      
      console.log("执行用户查询，参数:", this.userQueryParams);
      this.loadUserList();
    },
    
    /** 用户重置查询按钮操作 */
    handleUserReset() {
      this.userQueryParams = {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined
      };
      this.loadUserList();
    },

    /** 处理用户选择变更 */
    handleUserSelectChange(selection) {
      this.selectedUsers = selection;
      if (selection.length > 0) {
        const user = selection[0];
        // 设置表单数据
        this.memberForm.employee_id = user.userId;
        this.memberForm.employee_name = user.userName;
        this.memberForm.nickname = user.nickName || user.nickname || user.userName;
        this.memberForm.department = user.dept ? user.dept.deptName : '';
        this.memberForm.phone = user.phonenumber;
      }
    },

    /** 选择员工 */
    selectUser(row) {
      // 填充成员表单数据
      this.memberForm.employee_id = row.userId;
      this.memberForm.employee_name = row.userName;
      this.memberForm.nickname = row.nickName || row.nickname || row.userName;
      this.memberForm.department = row.dept ? row.dept.deptName : '';
      this.memberForm.phone = row.phonenumber;
      
      // 直接添加到班组成员列表
      this.teamMembers.push({
        employee_id: row.userId,
        employee_name: row.userName,
        nickname: row.nickName || row.nickname || row.userName,
        department: row.dept ? row.dept.deptName : '',
        phone: row.phonenumber
      });
      
      // 关闭对话框并提示成功
      this.userSelectVisible = false;
      this.$modal.msgSuccess("成员添加成功");
    },

    /** 确认选择员工 */
    confirmSelectUsers() {
      if (this.selectedUsers.length === 0) {
        this.$modal.msgError("请至少选择一个员工");
        return;
      }
      
      // 将选中的员工转换为需要的格式后添加到班组成员列表
      const newMembers = this.selectedUsers.map(user => ({
        employee_id: user.userId,
        employee_name: user.userName,
        nickname: user.nickName || user.nickname || user.userName,
        department: user.dept ? user.dept.deptName : '',
        phone: user.phonenumber
      }));
      
      this.teamMembers = [...this.teamMembers, ...newMembers];
      this.userSelectVisible = false;
      this.$modal.msgSuccess("已添加 " + newMembers.length + " 名成员");
    },

    /** 检测班组人员变化 */
    detectTeamMemberChanges() {
      // 比较原始班组人员和当前班组人员是否有变化
      if (this.originalTeamMembers.length !== this.teamMembers.length) {
        return true; // 长度不同，肯定有变化
      }
      
      // 比较每个成员的ID是否有变化（深度比较较复杂，这里只比较ID）
      const originalIds = this.originalTeamMembers.map(member => member.employee_id).sort();
      const currentIds = this.teamMembers.map(member => member.employee_id).sort();
      
      for (let i = 0; i < originalIds.length; i++) {
        if (originalIds[i] !== currentIds[i]) {
          return true; // 发现不匹配的ID，有变化
        }
      }
      
      return false; // 没有检测到变化
    },
    
    /** 获取生产线选项 */
    getProductionLineOptions(workshopId) {
      if (!workshopId) {
        console.warn("没有车间ID，无法获取生产线选项");
        return;
      }
      
      // 清空生产线选项
      this.productionLineOptions = [];
      
      // 获取生产线选项
      getlines({
        basicWorkshop: {
          workshop_id: workshopId
        },
        is_delete: 0
      }).then(response => {
        console.log("获取生产线选项响应:", response);
        if (response.code === 200) {
          // 处理不同的数据结构
          if (response.rows && Array.isArray(response.rows)) {
            this.productionLineOptions = response.rows;
          } else if (response.data && Array.isArray(response.data)) {
            this.productionLineOptions = response.data;
          } else {
            console.warn("获取生产线数据格式异常");
          }
        } else {
          console.warn("获取生产线选项失败:", response.msg);
        }
      }).catch(error => {
        console.error("获取生产线选项失败:", error);
      });
    }
  }
};
</script>

<style scoped>
.mb10 {
  margin-bottom: 10px;
}
.flex {
  display: flex;
}
.justify-between {
  justify-content: space-between;
}
.searchbar-container {
  margin-bottom: 20px;
  padding: 15px;
  border-radius: 4px;
  background-color: #f8f8f9;
}
.search-container {
  margin-bottom: 20px;
  padding: 15px;
  border-radius: 4px;
  background-color: #f8f8f9;
  display: flex;
  align-items: center;
  justify-content: flex-start; /* Align items to the start */
}
.search-container .el-input,
.search-container .el-select {
  margin-right: 10px;
}
.search-container .el-button {
  margin-left: 10px;
}

/* New styles for dialog sections */
.section-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}
.section-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}
.blue-line {
  width: 4px;
  height: 16px;
  background-color: #409EFF;
  margin-right: 8px;
  border-radius: 2px;
}
.team-members-container {
  margin: 10px 0 20px 0;
  background-color: #fff;
}
.team-members-actions {
  margin-bottom: 10px;
  text-align: right;
}
.team-members-table {
  margin-bottom: 0;
}
.team-members-table .el-table__empty-block {
  height: 60px;
  min-height: 60px;
}
.team-members-table .el-table__empty-text {
  line-height: 60px;
  color: #909399;
}
</style>